import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/pinia/modules/user';
import tool from "@/utils/tool";

const request = axios.create({
  baseURL: import.meta.env.VITE_API_PATH,
  headers: {
    'Accept': 'application/json;charset=UTF-8',
    'Content-Type': 'application/json;charset=UTF-8'
  },
  timeout: 100000,
  withCredentials: true,
  crossDomain: true,
  responseType: 'json',
  responseEncoding: 'utf8'
});

request.interceptors.response.use(
  response => {
    return new Promise((resolve, reject) => {
      if (response.headers['content-type']
          && (response.headers['content-type'].startsWith("application/octet-stream")
            || response.headers['content-type'].startsWith("image/"))) {
        resolve(response);
      } else if (response.data) {
        const data = response.data;
        if (data.code) {
          if (data.code === "0") {
            ElMessage.error(data.message || '');
            reject(data);
          } else {
            resolve(data);
          }
        } else {
            resolve(response);
        }
      } else {
        resolve(response);
      }
    });
  },
  error => {
    if (!error.response) {
      console.log(error);
      ElMessage.error('请求出错，请稍候再试。');
      return;
    }

    switch (error.response.status) {
      case 401:
        try {
          const userStore = useUserStore();
          if (userStore.getUser().id) {
            ElMessage.error('登录超时，请重新登录！');
          }
          userStore.clearStorage();
        } catch (e) {
          console.log(e)
        }

        window.location.href = tool.getBaseUrl() + (window.location.search || '');
        break;
      case 403:
        ElMessage.error('权限不足，请与管理员联系！');
        break;
      case 404:
        ElMessage.error('请求资源不存在！');
        break
      case 500:
        ElMessage.error('未知错误！');
        break
      default:
        ElMessage.error('未知错误！');
        break;
    }

    throw error
  }
);

export default request;
